package com.simen.downloader.util;

import android.content.Context;
import android.content.pm.PackageManager;

import com.simen.downloader.model.LocalFile;
import com.simen.downloader.naming.namegenerator.Md5FileNameGenerator;

import java.io.File;

/**
 * Created by zhangming on 16/4/25.
 */
public class FileStorageUtils {
    private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";

    public final static String DOWNLOAD = "downloadFileByWebview";

    public static File getBaseDir(Context context) {
        return context.getExternalFilesDir(DOWNLOAD);
    }

    public static File getDefaultFilePath(String dir, String key) {
        return new File(dir, getGenerateName(key));
    }

    private static String getGenerateName(String key) {
        return new Md5FileNameGenerator().generate(key);
    }

    public static File getDefaultFilePath(File dir, String key) {
        return new File(dir, getGenerateName(key));
    }

    public static File getDefaultLogFilePath(String dir, String key) {
        return new File(dir, getGenerateName(key) + Constants.LOGEXT);
    }

    public static File getDefaultLogFilePath(File dir, String key) {
        return new File(dir, getGenerateName(key) + Constants.LOGEXT);
    }

    private static boolean hasExternalStoragePermission(Context context) {
        int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
        return perm == PackageManager.PERMISSION_GRANTED;
    }

    public static void clearFile(String fileDir, String fileUrl) {
        Utils.deleteFile(getDefaultFilePath(new File(fileDir), fileUrl));
        Utils.deleteFile(getDefaultLogFilePath(new File(fileDir), fileUrl));
    }

    public static LocalFile getLocalFile(File dir, String fileUrl) {
        return new LocalFile(getDefaultFilePath(dir, fileUrl).getPath(), fileUrl);
    }

}
